" ██╗  ███╗   ██╗  ██╗  ████████╗  ██╗   ██╗  ██╗  ███╗   ███╗ ██╗
" ██║  ████╗  ██║  ██║  ╚══██╔══╝  ██║   ██║  ██║  ████╗ ████║ ██║
" ██║  ██╔██╗ ██║  ██║     ██║     ██║   ██║  ██║  ██╔████╔██║ ██║
" ██║  ██║╚██╗██║  ██║     ██║     ╚██╗ ██╔╝  ██║  ██║╚██╔╝██║ ╚═╝
" ██║  ██║ ╚████║  ██║     ██║ ██╗  ╚████╔╝   ██║  ██║ ╚═╝ ██║ ██╗
" ╚═╝  ╚═╝  ╚═══╝  ╚═╝     ╚═╝ ╚═╝   ╚═══╝    ╚═╝  ╚═╝     ╚═╝ ╚═╝

" ✧*｡٩(ˊᗜˋ*)و✧*｡
"
" vim插件
let g:StatusIcon = 0 " Status 图标是否常亮
let g:themes     = 1 " 0 表示 deus配色 1 表示 catppuccin 配色
let g:backgrond  = 1 " 0 dark 1 light
" 设置 1 为透明窗口
let g:coc_flaot_opacity = 0

lua require('init')

set re=0
set exrc
set secure
set tw=0
" set laststatus=0
set indentexpr=
set foldlevel=99
set foldenable
set formatoptions-=tc
set noshowmode
let &t_ut=''
set viewoptions=cursor,folds,slash,unix
set visualbell
set mouse=" "                      " 关闭鼠标支持
set encoding=utf-8                 " 编码格式
" set mouse=a                      " 开启鼠标支持
" set colorcolumn=100              " 标尺线
set lazyredraw
set history=30                     " 保留x行命令历史
" set number                         " 行号
" set relativenumber
set inccommand=nosplit
set termguicolors                  " 终端更好的颜色
set cursorline                     " 当前行高亮
set ignorecase                     " 搜索不在意大小写
set smartcase
set wrap                           " 设置换行
set expandtab                      " 缩进
set tabstop=4
set shiftwidth=4
set softtabstop=5
" set list                         " 缩进显示
" set listchars=tab:\|\ ,trail:▫
" set listchars=tab:»·,nbsp:+,trail:·,extends:→,precedes:←
set splitbelow                     " 分屏后光标自动到刚分出来的屏幕
set splitright
set clipboard=unnamedplus          " 和系统用一个剪切板
set scrolloff=8                    " 当vim下面剩下x行时窗口移动
set foldmethod=indent              " 代码折叠
set foldlevelstart=99              " 折叠宽度
set hidden                         " coc.nvim的推荐配置
set signcolumn=yes
set shortmess+=c
set updatetime=10
set autochdir                      " 修改vim的项目概念
" set showtabline=2                  " 标签页
set inccommand=split               " 搜索时预览
let mapleader=" "                  " 把leader设置为空格
set virtualedit=block
set pumheight=10
" let loaded_matchparen=1            " 取消括号的高亮
syntax enable                      " 高亮
syntax sync minlines=100
filetype on
filetype plugin on
filetype indent on
" 设置vim打开一个文件的时候光标会回到上一次存在的地方
augroup _cursor
    autocmd!
    autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
augroup end
" 打开文件vim会自动跳到此目录
augroup _bufdir
    autocmd!
    autocmd BufEnter * silent! cd %:p:h
augroup end
" 保存历史修改记录
if has("persistent_undo")
   let target_path = expand('~/.undodir')
    if !isdirectory(target_path)
        call mkdir(target_path, "p", 0700)
    endif
    let &undodir=target_path
    set undofile
endif
function _Dundodir() abort
    :sp
    :res -15
    :term rm -rf ~/.undodir && print "历史记录,删除成功"
endfunction
command Dundodir call _Dundodir()
" echo &filetype  " 输出当前文件类型
" set guicursor=n-v-c:block                  " 光标始终为块
" set signcolumn=number                      " 行号共用
" set guicursor=r-cr:hor20,o:hor50 " 设置光标样式


" fcitx5 中文输入法切换
let g:input_toggle = 0
function! Fcitx2en()
   let s:input_status = system("fcitx5-remote")
   if s:input_status == 2
      let g:input_toggle = 1
      let l:a = system("fcitx5-remote -c")
   endif
endfunction
function! Fcitx2zh()
   let s:input_status = system("fcitx5-remote")
   if g:input_toggle == 1
      let l:a = system("fcitx5-remote -o")
      let g:input_toggle = 0
   endif
endfunction
" set ttimeoutlen=100
"退出插入模式
augroup _Fcitx2en
    autocmd!
    autocmd InsertLeave * call Fcitx2en()
augroup END
"进入插入模式
augroup _Fcitx2zh
    autocmd!
    autocmd InsertEnter * call Fcitx2zh()
augroup END


" ==================== 模板 ====================
" source $HOME/.config/nvim/template.vim


" ==================== 快捷键 ====================
" 光标移动
map <S-l> g$
vnoremap <S-l> g$<left>
map <S-h> g^
" map <C-j> 3j
" map <C-k> 3k
map <C-k> kkk
map <C-j> jjj
map <C-l> 4l
map <C-h> 4h
" nmap j <Plug>(accelerated_jk_gj_position)
" nmap k <Plug>(accelerated_jk_gk_position)
nmap j gj
nmap k gk
vmap j gj
vmap k gk
nnoremap <M-h> <C-w>h
nnoremap <M-l> <C-w>l
nnoremap <M-j> <C-w>j
nnoremap <M-k> <C-w>k

cnoremap <M-i> <Home>
cnoremap <M-a> <End>
cnoremap <M-k> <Up>
cnoremap <M-j> <Down>
cnoremap <M-h> <Left>
cnoremap <M-l> <Right>
" ==================== 垂直光标移动 ====================
" 把 a s d f g h j k l ; 当作数字键来使用
" 为 1 2 3 4 5 6 7 8 9 0
" source $HOME/.config/nvim/cursor.vim

" nnoremap fd /\(\<\w\+\>\)\_s*\1<CR>

" Inspect 查询高亮
nnoremap <F9> :Inspect<CR>

" nnoremap Q :q<CR>
nnoremap Q :bd %<CR>
nnoremap S :w<CR>
nnoremap <C-o> <C-o>"myy
nnoremap <C-i> <C-i>"myy


" 防止 fzf.vim 弹出 Window
cnoreabbrev W w

" 退出当前 buffer
" cnoreabbrev Q bd %


" :%s/要替换的文本/要修改为的文本
" gqq 可以整理一个长的文本
" g~~  可以让一行文本大写
" gv 可以跳到上一次选中的文本
" imap <C-r>= 计算数字
" imap <C-v>u字符的编码 可以打印出一个字符
" map ga 查看字符编码
" map gR 进入替换模式
" . 可以多次使用上一个命令
" 可视模式 o 可以进行前后的跳跃
" S ranger进入目录

nnoremap <F11> a<C-r>=
inoremap <F11> <C-r>=

" 滚动
nnoremap <C-a> <C-u>
nnoremap <C-u> 15<C-y>
nnoremap <C-b> 15<C-e>
vnoremap <C-a> <C-u>
vnoremap <C-u> <C-b>
vnoremap <C-b> <C-f>
nnoremap <C-e> <C-e>

" 查找
nnoremap n nzz
nnoremap N Nzz


inoremap <C-d> <ESC>A
inoremap <C-a> <ESC>I



"  ``
inoremap <M-'> ``<ESC>i


" 删除下一行
" nnoremap <C-n> jddk
" nnoremap <C-p> kdd


" 单词操作
nnoremap dw diw
nnoremap diw "_diw
nnoremap d" "_di"
nnoremap d` di`
nnoremap cw "_ciw
nnoremap c( ci(
nnoremap c' ci'
nnoremap c" ci"
nnoremap c{ ci{
nnoremap c` ci`
nnoremap vw viw
nnoremap yw yiw
nnoremap v` vi`


" 查找替换
nnoremap \s :%s//g<left><left>
vnoremap \s :s//g<left><left>

" 缩进
nnoremap < <<
nnoremap > >>
vnoremap > >gv
vnoremap < <gv

" 选中后对选中的一块区域进行上下移动
vnoremap <M-j>  :m '>+1<CR>gv=gv
vnoremap <M-k>  :m '<-2<CR>gv=gv
vnoremap <down> :m '>+1<CR>gv=gv
vnoremap <up>   :m '<-2<CR>gv=gv


" 撤销
inoremap <C-z> <Esc>ua


" 调整窗口
nnoremap <UP>    :res +1<CR>:res +1<CR>:res +1<CR>
nnoremap <down>  :res -1<CR>:res -1<CR>:res -1<CR>
nnoremap <Left>  :vertical resize-1<CR>:vertical resize-1<CR>:vertical resize-1<CR>
nnoremap <right> :vertical resize+1<CR>:vertical resize+1<CR>:vertical resize+1<CR>



" 刷新配置
" map R :source $MYVIMRC<CR>
" nnoremap <F5> :source $MYVIMRC<CR>



" 单词诊断
nnoremap <space>sh :set spell<CR>
" 单词补全
" inoremap <C-x> <Esc>ea<C-x>s

" 关闭搜索高亮
" nnoremap <space>q :nohlsearch<CR>
nnoremap R :nohlsearch<CR>


" 缓冲区
nnoremap <space>l :bn<CR>
nnoremap <space>h :bp<CR>



" 标签页
noremap tu :tabe<CR>
noremap <space>u :tabe<CR>
noremap ti :tabe<CR>
noremap <space>i :tabe<CR>
" noremap tI :tab split<CR>
noremap tU :tab split<CR>
noremap gh :-tabnext<CR>
noremap <space>j :-tabnext<CR>
noremap gl :+tabnext<CR>
noremap <space>k :+tabnext<CR>
noremap tmj :-tabmove<CR>
noremap tmk :+tabmove<CR>



" 防止退出vim
map <C-z> <nop>


" r 进行文本替换
nnoremap <space>r r
vnoremap <space>r r



" 窗口
nnoremap sh :vsp<CR>
nnoremap sp :sp<CR>
nnoremap sk <C-w>t<C-w>H<CR>
nnoremap sj <C-W>t<C-w>K<CR>
function VspTerm()
    :vsp
    :term
endfunction
cnoreabbrev vst call VspTerm()
nnoremap th :call VspTerm()<CR>a

function SpTerm()
    :sp
    :term
endfunction
cnoreabbrev st call SpTerm()
nnoremap st :call SpTerm()<CR>a

function StFloat() abort
    :! sh -c 'st -c float'
endfunction
nnoremap \t :call StFloat()<CR>
" nnoremap \t :tabe<CR>:-tabmove<CR>:term sh -c 'st -c float'<CR><C-\><C-N>:q<CR>

" 调整数字的大小
nnoremap + <C-a>
nnoremap _ <C-x>



" {} Brackets
" inoremap <C-j> <ESC>A {}<ESC>i<CR><ESC>ko
" inoremap <C-l> <ESC>A {}<ESC>i<CR><ESC>"myyko
" vnoremap <C-f> I<CR><ESC>gv>I{<ESC>gvg$A<ESC>A<CR>}<++><ESC>gvI<ESC>gv"my<ESC>$i
" inoremap <C-l> <ESC>A<space>{}<ESC>i<CR><ESC>"myyko
inoremap <C-f> <ESC>A}<ESC>I{<CR><ESC>A<ESC>i<CR><ESC>a<space><++><ESC>k<ESC>ki<space><ESC>i<space>(<++>)<ESC>bhi
vnoremap <C-f> I<CR><ESC>gv>I{<ESC>gvg$A<ESC>A<CR>}<ESC>gvI<ESC>gv"my<ESC>$i

" jk 切换 模式
" imap jk <Esc>
" 快速查找<++>并进行替换
" 查找距离最近的 <++>
nnoremap <space><TAB> i<C-R>=Search_word()<CR>
" 代码片段操作
" inoremap <C-j> <Esc>/<++><CR>:nohlsearch<CR>"_c4l<ESC>"myya
" 正常搜索会污染搜索器 和剪切板
function! Search_word() abort
    if search('<++>', 'w')
        return "\<ESC>eF<\"_c4l\<ESC>\"myya"
    else
        return "\<ESC>"
    endif
endfunction
inoremap <C-j> <C-R>=Search_word()<CR>


" ==================== 运行代码 ====================
noremap r :call CompileRunGcc()<CR>
" 关闭终端的行号显示
augroup _TermOpenNumbers
    autocmd!
    autocmd TermOpen * setlocal nonumber norelativenumber
augroup END
function SplitScreen() abort
    :sp
    :res -5
endfunction
func! CompileRunGcc()
	exec "w"
	if &filetype == 'c'
        :call SplitScreen()
		:term gcc % -o %< && ./%<
		" :term gcc % -o %< && time ./%<
	elseif &filetype == 'cpp'
		exec "!g++ -std=c++11 % -Wall -o %<"
        :call SplitScreen()
		:term ./%<
	elseif &filetype == 'cs'
		silent! exec "!mcs %"
        :call SplitScreen()
		:term mono %<.exe
    elseif &filetype == 'lua'
        :call SplitScreen()
        :term lua %
    elseif &filetype == 'vim'
        :call SplitScreen()
        :term source %
	elseif &filetype == 'java'
        :call SplitScreen()
		term javac % && time java %<
	elseif &filetype == 'sh'
        :call SplitScreen()
        :term bash %
	elseif &filetype == 'python'
        :call SplitScreen()
		:term python3 %
	elseif &filetype == 'html'
		silent! exec "!google-chrome-stable % &"
	elseif &filetype == 'markdown'
        exec "MarkdownPreview"
	elseif &filetype == 'tex'
		silent! exec "VimtexStop"
		silent! exec "VimtexCompile"
	elseif &filetype == 'dart'
		exec "CocCommand flutter.run -d ".g:flutter_default_device." ".g:flutter_run_args
		silent! exec "CocCommand flutter.dev.openDevLog"
	elseif &filetype == 'javascript'
        :call SplitScreen()
        :term node %
	elseif &filetype == 'typescript'
        :call SplitScreen()
		:term ts-node %
	elseif &filetype == 'racket'
        :call SplitScreen()
		term racket %
	elseif &filetype == 'go'
        :call SplitScreen()
		:term go run %
	endif
endfunc

let g:flutter_default_device = 'Redmi\ K40'
let g:flutter_run_args = "--flavor dev"


" vimscript编写的,快速删除html属性功能
function SelectAttr(space)
	let res = GetEqIdx()
	let idx = res[0]
	let is_double = res[1]
	" 当光标当前行没有能删除的 html属性时
	" 将会弹出 invalide operation
	if idx == -1
		echo 'invalide operation'
		return
	endif

	let has = 0
	if a:space
		call cursor('.', idx + 1)
		norm! B
		let col_idx = getcurpos()[2] - 2
		let ln = getline('.')

		if ln[col_idx] == ' '
			let has = 1
		else
			if is_double
				norm! f"f"
			else
				norm! f'f'
		endif
			let col_idx = getcurpos()[2]
			if ln[col_idx] == ' '
				let has = 2
			endif
		endif
	endif
	call cursor('.', idx + 1)

	" 使用B 是因为对 xxx-xxx 这种类型的命名或者其他的会有效的删除
	" 如果是使用 b 则只会删除 xxx-xxx 其中 - 后面或者前面一端的文本
	if has == 0
		if is_double
			norm! vf"f"oB
		else
			norm! vf'f'oB
		endif
	elseif has == 1
		if is_double
			norm! vf"f"oBh
		else
			norm! vf'f'oBh
		endif
	else
		if is_double
			norm! vf"f"loB
		else
			norm! vf'f'loB
		endif
	endif
endfunction


" vim html属性快速删除功能
function GetEqIdx()
	let ln = getline('.')
	let len = len(ln)
	let col_idx = getcurpos()[2] - 1
	let ret = -1
	let is_double = 0

	if ln[col_idx] == '='
		let ret = col_idx
	endif

	let idx = col_idx
	while idx < len
		let c = ln[idx]

		if c == '='
			let ret = idx
		elseif c == '"' || c == "'"
			if ret != -1
				return [ret, c == '"']
			endif

			let is_double = c == '"'
			break
		endif
		let idx += 1
	endwhile

	let idx = col_idx
	while idx > -1
		if ln[idx] == '='
			return [idx, is_double]
		endif
		let idx -= 1
	endwhile
	return [-1,0]
endfunction


" " ==================== 设置vim的主题 ====================
" 主题类型
try
    if g:themes < 1
        colorscheme vim-deus
        " colorscheme deus
        let g:indentLine_color_gui = '#211a32'
    elseif g:themes == 1
        colorscheme catppuccin
        " javascript lsp highlight
        highlight! link @function.builtin function
    elseif g:themes == 2
        " highlight! link TelescopeSelection TelescopePreviewMatch
        " colorscheme default
        " colorscheme base16-brewer
        " colorscheme alabaster
        highlight CocMenuSel ctermbg=237 guibg=NvimLightGrey2 guifg=#000000
        highlight Statusline guibg=Normal guifg=NvimLightGrey2
        highlight! Normal guibg=#000000
        " highlight!  Function guifg=#ffffcc gui=bold
    elseif g:themes == 3
        colorscheme everforest
    elseif g:themes == 4
        colorscheme doom-one
    elseif g:themes == 5
        colorscheme nordic
    endif
endtry

" colorscheme github_dark
if g:backgrond == 0
    set background=light
endif


" ==================== vim中文文档支持 ====================
let helptags=$VIM."/vimfiles/doc"
set helplang=cn


" ==================== suda.vim ====================
cnoreabbrev sudowrite w suda://%
cnoreabbrev sw w suda://%


" ==================== tabular ====================
vnoremap ga :Tabularize /


" ====================  vim-floaterm ====================
noremap tt :FloatermNew<CR>
tnoremap <C-q> exit<CR>
" ==================== lazygit ====================
noremap <space>p :FloatermNew lazygit<CR>
" ==================== ranger ====================
noremap <space>R :FloatermNew ranger<CR>
" noremap <space>R :FloatermNew nvim<CR>e:DBUI<CR>
" ==================== fzf ====================
command FZF FloatermNew fzf


" " ==================== fzf.vim ====================
" " let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6} }
" let g:fzf_layout = { 'down': '35%' }
" let g:fzf_preview_window = ''
" " let g:fzf_action = { 'ctrl-e': 'edit' }
"
" " let g:fzf_preview_window = ['right,50%,<60(down,50%)', 'ctrl-/']
" let g:fzf_commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"'
" func! RipgrepFzf(query, fullscreen)
"   let command_fmt = 'rg --color=always --column --line-number --no-heading --smart-case'
"   let command_fmt .= ' --glob "!vendor" --glob "!node_modules"'
"   let command_fmt .= ' --colors "path:fg:blue" --colors "path:style:bold"'
"   let command_fmt .= ' --colors "match:fg:151"'
"   let command_fmt .= ' -- %s || true'
"   let initial_command = printf(command_fmt, shellescape(a:query))
"   let reload_command = printf(command_fmt, '{q}')
"   let spec = {'options': ['--disabled', '--query', a:query, '--bind', 'change:reload:'.reload_command]}
"   let spec = fzf#vim#with_preview(spec, 'right,50%,<50(down,50%)', 'ctrl-/')
"   call fzf#vim#grep(initial_command, 1, spec, a:fullscreen)
" endf
"
" com! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)
"
" " cnoreabbrev FZF Files
"
" nnoremap P :History<CR>
" nnoremap <C-f> :Files<CR>
" nnoremap sl :BLines<CR>
" nnoremap <space>b :Buffers<CR>
" nnoremap sg :RG<CR>


" func! CHistory()
"   call filter(v:oldfiles, "v:val =~ '^' . $PWD . '.*$'")
"   call fzf#vim#history(fzf#vim#with_preview(), 0)
" endf
"
" com! CHistory call CHistory()



"  ==================== vim-visual-multi ====================
let g:VM_maps                       = {}
let g:VM_maps['Find Under']         = '<C-s>'
let g:VM_maps['Find Subword Under'] = '<C-s>'
let g:VM_maps['Remove Region']      = 'q'
let g:VM_maps['Skip Region']        = 'n'

" ==================== Antovim ====================
nnoremap sw :Antovim<cr>


"  ==================== undotree ====================
nnoremap sc :UndotreeToggle<CR>

" ==================== Terminal Colors ====================
let g:terminal_color_0  = '#000000'
let g:terminal_color_1  = '#FF5555'
let g:terminal_color_2  = '#50FA7B'
let g:terminal_color_3  = '#F1FA8C'
let g:terminal_color_4  = '#BD93F9'
let g:terminal_color_5  = '#FF79C6'
let g:terminal_color_6  = '#8BE9FD'
let g:terminal_color_7  = '#BFBFBF'
let g:terminal_color_8  = '#4D4D4D'
let g:terminal_color_9  = '#FF6E67'
let g:terminal_color_10 = '#5AF78E'
let g:terminal_color_11 = '#F4F99D'
let g:terminal_color_12 = '#CAA9FA'
let g:terminal_color_13 = '#FF92D0'
let g:terminal_color_14 = '#9AEDFE'

" jsx syntax
" augroup _JSX_TSX_Syntax
"     autocmd!
"     autocmd BufNewFile,BufRead *.tsx,*.jsx set syntax=html
"     autocmd BufNewFile,BufRead *.tsx,*.jsx set syntax=typescriptreact
"     autocmd BufNewFile,BufRead *.less set syntax=css
" augroup END

" html javascript syntax
" augroup _FileSyntax
"     autocmd!
"     autocmd! Syntax html,vue   syntax sync fromstart
" augroup end

augroup _Start
    autocmd!
    autocmd Syntax jsx highlight! link jsxTagName htmlTagName
    " highlight! link jsxClosePunct htmlTag
augroup END
